﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Models
{
    public class Manager
    {
        public String ProjectsDirectoryPath { get; set; }
        public String CurrentSessionPath { get; set; }

        public Session ReadSession()
        {
            var path = String.Format("{0}\\{1}", CurrentSessionPath, "Session.ism");
            if (!File.Exists(path))
            {
                MessageBox.Show("The file doesn't exists.");
                return null;
            }

            var stream = File.Open(path, FileMode.Open);
            var bformatter = new BinaryFormatter();

            var session = (Session)bformatter.Deserialize(stream);
            stream.Close();

            return session;
        }

        public void SaveSession(Session Session, String path = null)
        {
            if (Session == null)
                return;

            if (path == null)
                path = String.Format("{0}\\{1}", CurrentSessionPath, "Session.ism");

            var stream = File.Open(path, FileMode.Create);
            var bformatter = new BinaryFormatter();

            bformatter.Serialize(stream, Session);
            stream.Close();
        }

        public void SaveIdeaList(List<Idea> IdeaList, String path = null)
        {
            if (IdeaList == null)
                return;
            if (path == null)
                path = String.Format("{0}\\{1}", CurrentSessionPath, "Idea.data");

            var stream = File.Open(path, FileMode.Create);
            var bformatter = new BinaryFormatter();

            bformatter.Serialize(stream, IdeaList);

            stream.Close();
        }

        public void SaveParticipantList(List<Participant> ParticipantList, String path = null)
        {
            if (ParticipantList == null)
                return;
            if (path == null)
                path = String.Format("{0}\\{1}", CurrentSessionPath, "Part.data");

            var stream = File.Open(path, FileMode.Create);
            var bformatter = new BinaryFormatter();

            bformatter.Serialize(stream, ParticipantList);

            stream.Close();
        }


        public void SetSessionPath(String sessionName)
        {
            CurrentSessionPath = String.Format("{0}\\{1}", ProjectsDirectoryPath, sessionName);
        }

        public bool ValidateSessionName(String sessionName)
        {

            var path = String.Format("{0}\\{1}", ProjectsDirectoryPath, sessionName);
            return (!Directory.Exists(path));
        }


        public Session CreateSessionFiles(String sessionName)
        {
            //Create Directories
            if (!Directory.Exists(ProjectsDirectoryPath)) { Directory.CreateDirectory(ProjectsDirectoryPath); }
            var sessionDirectory = Directory.CreateDirectory(CurrentSessionPath);
            //Create Default session files

            var sessionFilePath = String.Format("{0}\\{1}", CurrentSessionPath, "Session.ism");
            var participantsFilePath = String.Format("{0}\\{1}", CurrentSessionPath, "Part.data");
            var ideasFilePath = String.Format("{0}\\{1}", CurrentSessionPath, "Idea.data");
            var configurationFilePath = String.Format("{0}\\{1}", CurrentSessionPath, "Conf.data");

            File.Create(sessionFilePath).Close();
            File.Create(participantsFilePath).Close();
            File.Create(ideasFilePath).Close();
            File.Create(configurationFilePath).Close();

            var createdSession = new Session
                                     {
                                         SessionName = sessionName,
                                         SessionPath = CurrentSessionPath
                                     };
            SaveSession(createdSession, sessionFilePath);

            return createdSession;
        }

        public List<Idea> ReadSessionIdeas()
        {
            var path = String.Format("{0}\\{1}", CurrentSessionPath, "Idea.data");
            if (!File.Exists(path))
            {
                MessageBox.Show("The file doesn't exists.");
                return null;
            }

            var stream = File.Open(path, FileMode.Open);
            var bformatter = new BinaryFormatter();

            var ideas = (List<Idea>)bformatter.Deserialize(stream);
            stream.Close();

            return ideas;
        }

        public List<Participant> ReadSessionParticipants()
        {
            var path = String.Format("{0}\\{1}", CurrentSessionPath, "Part.data");
            if (!File.Exists(path))
            {
                MessageBox.Show("The file doesn't exists.");
                return null;
            }

            var stream = File.Open(path, FileMode.Open);
            var bformatter = new BinaryFormatter();

            var participants = (List<Participant>)bformatter.Deserialize(stream);
            stream.Close();

            return participants;
        }

        public Manager()
        {
            try
            {
                var applicationDirectory = AppDomain.CurrentDomain.GetAssemblies()
                                                    .Where(i => i.CodeBase.EndsWith(".exe"))
                                                    .Select(i => System.IO.Path.GetDirectoryName(i.CodeBase.Replace("file:///", "")))
                                                    .FirstOrDefault();
                ProjectsDirectoryPath = String.Format("{0}\\{1}", applicationDirectory, "Projects");
            }
            catch (Exception e)
            {
                ProjectsDirectoryPath = String.Empty;
            }

        }


        public string GetSafeFilename(string filename)
        {
            return String.Join("_", filename.Split(Path.GetInvalidFileNameChars()));
        }
    }
}
